package com.yylending.las.webview;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.ViewGroup;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.R;
import com.yylending.las.YJKD;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.main.MainActivity;
import com.yylending.las.personal.feedback.FeedbackActivity;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by HenryZhang on 2016/11/2.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 * <p>
 * for android:
 * https://github.com/lzyzsd/JsBridge
 * <p>
 * http://blog.csdn.net/sbsujjbcy/article/details/50752595
 * http://blog.csdn.net/zhazha12/article/details/51736775
 * http://www.jianshu.com/p/b3d120753bbb
 * https://github.com/pengwei1024/JsBridge
 * https://github.com/pedant/safe-java-js-webview-bridge
 * https://labs.mwrinfosecurity.com/blog/building-android-javajavascript-bridges/
 * <p>
 * for iOS:
 * https://github.com/marcuswestin/WebViewJavascriptBridge
 * <p>
 * http://www.jianshu.com/p/ca496cb680fe
 * <p>
 * android.os.Process.killProcess(android.os.Process.myPid());
 * System.exit(1);
 */
public class WebViewActivity extends BaseActivity implements WebViewPresenter.View {
	private final static String TAG = "WebViewActivity";

	private final static int LOADER_ID = 205;
	public final static String INSTANCE_TITLE = "instance_title";
	public final static String INSTANCE_TYPE = "instance_type";
	public final static String INSTANCE_URL = "instance_url";
	public final static String INSTANCE_NEED_SIG = "instance_need_sig";
	public final static String INSTANCE_RIGHT_IMG = "instance_right_image";
	public final static String INSTANCE_RIGHT_TEXT = "instance_right_text";

	private WebViewPresenter mPresenter;

	private BridgeWebView mBrowser;

	private String mUrl = "";
	private String mTitle = "";
	private int mRightImgId = -1;
	private String mRightText = "";

	public static void start(Activity aty, String url, String title, int rightIconId) {
		Intent intent = new Intent(aty, WebViewActivity.class);
		intent.putExtra(WebViewActivity.INSTANCE_URL, url);
		intent.putExtra(WebViewActivity.INSTANCE_TITLE, title);
		intent.putExtra(WebViewActivity.INSTANCE_RIGHT_IMG, rightIconId);
		aty.startActivity(intent);
	}

	public static void start(Activity aty, String url, String title, String rightText) {
		Intent intent = new Intent(aty, WebViewActivity.class);
		intent.putExtra(WebViewActivity.INSTANCE_URL, url);
		intent.putExtra(WebViewActivity.INSTANCE_TITLE, title);
		intent.putExtra(WebViewActivity.INSTANCE_RIGHT_TEXT, rightText);
		aty.startActivity(intent);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		CLog.i(TAG, "WebViewActivity onLoadFinished");
		mPresenter = (WebViewPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int i, Bundle bundle) {
		return new PresenterLoader<>(this, new WebViewPresenter.Generator());
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mBrowser != null)
			mBrowser.reload();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mBrowser != null)
			mBrowser.onResume();
		handleIntent();
	}

	@Override
	protected void onPause() {
		if (mBrowser != null)
			mBrowser.onPause();
		super.onPause();
	}

	@Override
	protected void onStop() {
		if (mBrowser != null)
			mBrowser.stopLoading();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		getSupportLoaderManager().destroyLoader(LOADER_ID);
		if (mBrowser != null) {
			((ViewGroup) mBrowser.getParent()).removeView(mBrowser);
			mBrowser.removeAllViews();
//			mWebView.onPause();
			mBrowser.destroy();
		}
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		//在条件满足时开启硬件加速
		try {
			if (Integer.parseInt(android.os.Build.VERSION.SDK) >= Build.VERSION_CODES.HONEYCOMB) {
				getWindow().setFlags(
						android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
						android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
			}
		} catch (Exception e) {
			CLog.i(TAG, "can't open hardware accelerated:" + e.getMessage());
		}
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
		setContentView(R.layout.activity_webview);
		initWebView();
	}

	@Override
	protected void onBackBtnPressed() {
		goBack();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		goBack();
	}

	private void goBack() {
		if (mBrowser != null && mBrowser.canGoBack()) {
			mBrowser.goBack();// 返回前一个页面
		} else {
			finish();
		}
	}


	private void initWebView() {
//		View root = findViewById(R.id.web_view_root);
//		root.getViewTreeObserver().addOnGlobalLayoutListener(new WebViewKeyboardObserver(root));

		mBrowser = (BridgeWebView) findViewById(R.id.web_view);
		if (mBrowser == null)
			return;

		WebViewSetter.setDownloadListener(this, mBrowser);
		WebViewSetter.supportChromeDebug(mBrowser);
		WebViewSetter.setting(this, mBrowser.getSettings());
		//WebViewSetter.addJavascriptInterface(this, mBrowser, "APPJsBridge");

		// 设置setWebChromeClient对象
//		mBrowser.setWebChromeClient(new WebChromeClient() {
//			@Override
//			public void onReceivedTitle(WebView view, String title) {
//				super.onReceivedTitle(view, title);
////				setActivityTitle(mTitle);
//			}
//
//			@Override
//			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//				return isFinishing() || super.onJsAlert(view, url, message, result);
//			}
//		});

//		mBrowser.setWebViewClient(new WebViewClient() {
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				boolean rs = WebViewSetter.shouldOverrideUrlLoading(WebViewActivity.this, url);
//				if (!rs) {
//					mUrl = url;
//				} else {
//
//				}
//				return rs;//true时在当前webview跳转
//			}
//
//			@Override
//			public void onPageFinished(WebView view, String url) {
//				CLog.i(TAG, "onPageFinished:url=" + url);
//				WebViewSetter.addImageClickListener(mBrowser);
//			}
//
//			@Override
//			public void onLoadResource(WebView view, String url) {// 每加载一个页面资源都会回调一次
//			}
//			@Override
//			public void onFormResubmission(WebView view, Message dontResend, Message resend) {//重新请求网页数据
//			}
//			@Override
//			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {//https请求
//			}
//			@Override
//			public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,String realm) {//返回信息授权请求
//			}
//			@Override
//			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {//页面错误信息
//			}
//			@Override
//			public void onUnhandledKeyEvent(WebView view, KeyEvent event) {//Key事件未被加载时调用
//			}
//			@Override
//			public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {//处理浏览器中的按键事件
//				return super.shouldOverrideKeyEvent(view, event);//false is default
//			}
//		});

//		mBrowser.callHandler("functionInJs", "", new CallBackFunction() {
//			@Override
//			public void onCallBack(String data) {
//				CLog.i(TAG, "handler name: functionInJs, data from web = " + data);
//			}
//		});
		mBrowser.registerHandler("APPJsBridge", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				CLog.i(TAG, "handler name: WebViewJavascriptBridge, data from web = " + data);
				function.onCallBack("WebViewJavascriptBridge exe, response data from Java");
			}
		});

		mBrowser.registerHandler("setPageTitle", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				CLog.i(TAG, "handler name=setPageTitle, data from web = " + data);
				function.onCallBack("setPageTitle exe, response data from Java");
				try {
					JSONObject obj = new JSONObject(data);
					String title = obj.optString("name");
					setTitle(title);
				} catch (JSONException e) {
					setTitle(getResources().getString(R.string.web_view));
				}
			}
		});
		mBrowser.registerHandler("requestData", new BridgeHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				CLog.i(TAG, "handler name=requestData, data from web = " + data);
				try {
					JSONObject obj = new JSONObject(data);
					String path = obj.optString("url");
					String method = obj.optString("type");
					String body = obj.optString("data");
					mPresenter.loadUrl(method, path, body, function);
				} catch (Exception e) {
					CLog.i(TAG, "handler name=requestData, Exception=" + e.getMessage());
				}
				//function.onCallBack("requestData exe, response data from Java");
			}
		});
	}

	private void handleIntent() {
		Intent i = getIntent();
		if (i != null) {
			mUrl = i.getStringExtra(INSTANCE_URL);
			mTitle = i.getStringExtra(INSTANCE_TITLE);
			mRightImgId = i.getIntExtra(INSTANCE_RIGHT_IMG, -1);
			mRightText = i.getStringExtra(INSTANCE_RIGHT_TEXT);
			if (!TextUtils.isEmpty(mTitle)) {
				setTitle(mTitle);
			}
			if (mRightImgId > -1) {
				showRightImg(mRightImgId);
			}
			if (!TextUtils.isEmpty(mRightText)) {
				setRightTx(mRightText);
				setRightTextVisible(true);
			}
		}
		if (!mUrl.isEmpty()) {
			mBrowser.loadUrl(mUrl);
//			mBrowser.loadData (html, "text/html", "UTF-8");
		}
	}

	@Override
	public void responseLoad(int type, String url) {

	}

	@Override
	public void responseData(String title, int commentType, int articleId) {

	}

	@Override
	public void loadFail(String msg) {
		showToast(msg);
	}

	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		if (getString(R.string.help_center).equals(mTitle)) {
			if (YJKD.login()) {    //登录了,跳反馈
				FeedbackActivity.start(this);
			} else {    //没登录,去登陆
				MainActivity.start(WebViewActivity.this, true);
			}
		}
	}
}
